package com.example.demo.thread;

import com.example.demo.service.DZDPScratchService;
import org.jsoup.HttpStatusException;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ZhengWei
 * @Description
 * @date 2020/7/15 9:58 上午
 */
public class CityTask implements Runnable {

    private DZDPScratchService scratchService;

    //线程编号
    private int threadCode;

    //当前线程任务数量
    private int taskNum;

    //菜品 id
    private Integer skuId;

    //数据库中城市 id 列表
    private Set<Integer> cityIdExist;

    //剩余总任务数量，多线程共享该数据
    private AtomicInteger cityNums;
    private AtomicInteger errorNum;

    public CityTask(DZDPScratchService scratchService, int threadCode, int taskNum, Integer skuId,Set<Integer> cityIdExist, AtomicInteger totalCityNum, AtomicInteger errorNum) {
        this.scratchService = scratchService;
        this.threadCode = threadCode;
        this.taskNum = taskNum;
        this.skuId = skuId;
        this.cityIdExist = cityIdExist;
        this.cityNums = totalCityNum;
        this.errorNum = errorNum;
    }

    @Override
    public void run() {
        /**
         * 每个线程执行被分配的任务
         * 如：总任务数为 5000 时，1 号线程执行 1-2500
         */
        int begin = taskNum * (threadCode - 1) + 1;
        int end = taskNum * threadCode;

        for (int i = begin; i <= end; i++) {
            try {
                if (!cityIdExist.contains(i)) {
                    scratchService.getCity(i, skuId);
                }
            } catch (IOException e) {
                HttpStatusException e1 = (HttpStatusException) e;
                if (e1.getStatusCode() == 403) {
                    System.out.print("禁止访问\t");
                    errorNum.getAndIncrement();
                } else if (e1.getStatusCode() == 404) {
                    System.out.print("没有该城市，或该城市没有 菜品 ID 为 " + skuId + " 的榜单\t");
                }
            }
            cityNums.getAndDecrement();
            System.out.println(Thread.currentThread()+"----剩余任务数："+cityNums);
        }
    }
}
